<?php

namespace app\admin\controller\game;

use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 游戏模式管理
 *
 * @icon fa fa-circle-o
 */
class Modes extends Backend
{

    /**
     * Modes模型对象
     * @var \app\common\model\game\Modes
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\game\Modes;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['lists'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {

            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            $inster = [];
            for ($i = 1; $i <= $params['capacity_num']; $i++) {//人数
                for ($is = 1; $is <= $params['capacity_num']; $is++) {//排名
                    $inster[] = [
                        'mode_id' => $this->model->id,
                        'ratio' => 0,
                        'rank_num' => $i,
                        'num' => $is
                    ];
                }
            }


//            $this->error("111", null, $inster);
            if (!empty($inster)) {
                Db::name('game_rank_ratio')->insertAll($inster);
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage(), null, $e->getTrace());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);

//        $specss = Db::name('game_rank_ratio')->where('mode_id', $row->id)->select();

        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $num = Db::name('game_modes')->where('id', $row->id)->value('capacity_num', 0);
        $data = [];

        for ($i = 0; $i < $num; $i++) {//$i 是排名
            $rank = $i + 1;
//            $data_index = $i;//人数
            $specs = Db::name('game_rank_ratio')->where(['mode_id' => $row->id, 'rank_num' => $rank])->order("num DESC")->select();
            foreach ($specs as $key => $items) {
                $data[$i]['id_' . $key] = $items['id'];
                $data[$i]['ratio_' . $key] = $items['ratio'];
                $data[$i]['rank_num_' . $key] = $items['rank_num'];//排名
                $data[$i]['num_' . $key] = $items['num'];//人数
//                $data_index++;
            }
        }

        $row->specs = $data;

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $spec = json_decode($params['spec'], true);

            foreach ($spec as $item) {
                for ($iss = 0; $iss < $params['capacity_num']; $iss++) {
                    Db::name('game_rank_ratio')->where(['id' => $item['id_' . $iss]])
                        ->update(['ratio' => $item['ratio_' . $iss]]);
                }
            }


//            if (max($ratio_all) > 100) {
//                throw new Exception("当前比例已超过百分百");
//            }
//            Db::name('game_rank_ratio')->where('mode_id', $row->id)->where("id", "NOT IN", $used)->delete();
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage(), "", $e->getTrace());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
}
